//
//  ViewController.m
//  随时随地测试项目
//
//  Created by 陈锋 on 2017/5/31.
//  Copyright © 2017年 陈志凌. All rights reserved.
//

#import "ZJloginViewController.h"
#import "ZJHomeViewController.h"
#import "ZJChangeProjectView.h"
#import "ZJShuRuTGMView.h"

//会员ID
NSString *allConstMemberid;
//会员实名
NSString *allConstAuthenticated;
//是否打开输入推广码界面
NSString *allOpen_promoter;
//项目id
NSString *allConstProjectid;
//色号
NSString *allConstHexColor;
//导航栏图片
NSString *allConstNavImgName;
//导航栏图片
NSString *allConstDocPath;
//app版本号 Version
NSString *appVersion;
//app的build号
NSString *appBuild;

@interface ViewController ()<UITextFieldDelegate,UINavigationControllerDelegate>
@property (weak, nonatomic) IBOutlet UIScrollView *scrollview;
//号码提示
@property (weak, nonatomic) IBOutlet UILabel *phoneLabel;
//号码输入框
@property (weak, nonatomic) IBOutlet UITextField *phoneText;
//验证码提示
@property (weak, nonatomic) IBOutlet UILabel *passLabel;
//验证码输入框
@property (weak, nonatomic) IBOutlet UITextField *passText;
//登录按钮
@property (weak, nonatomic) IBOutlet RNLoadingButton *loginBtn;

//输入图框
@property (weak, nonatomic) IBOutlet UIView *loginView;

@property (nonatomic,strong) MMDrawerController * drawerController;
@property (nonatomic,strong) ZJChangeProjectView * ChangeProjectView;
@property (nonatomic,strong) ZJShuRuTGMView *ShuRuTGMView;
@end

@implementation ViewController
{
    BOOL _wasKeyboardManagerEnabled;
}
-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    _wasKeyboardManagerEnabled = [[IQKeyboardManager sharedManager] isEnabled];
    [[IQKeyboardManager sharedManager] setEnable:NO];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(closeHMS) name:@"HMScannerViewClose" object:nil];
}
-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"HMScannerViewClose" object:nil];
    
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [[IQKeyboardManager sharedManager] setEnable:_wasKeyboardManagerEnabled];
}

-(ZJChangeProjectView *)ChangeProjectView{
    if (!_ChangeProjectView) {
        _ChangeProjectView = [[[NSBundle mainBundle] loadNibNamed:@"ZJChangeProjectView" owner:self options:nil] lastObject];
        
    }
    return _ChangeProjectView;
}
-(ZJShuRuTGMView *)ShuRuTGMView{
    if (!_ShuRuTGMView) {
        _ShuRuTGMView = [[[NSBundle mainBundle] loadNibNamed:@"ZJShuRuTGMView" owner:self options:nil] lastObject];
        
    }
    return _ShuRuTGMView;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    appVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    appBuild = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];
    //页面设置
    self.navigationController.delegate = self;
    
    self.loginView.layer.borderColor = [UIColor lightGrayColor].CGColor;
    self.loginView.layer.borderWidth = 1.0f;
    
    [self.loginBtn setBackgroundColor:[Utils colorWithHexString:@"e85855"]];

    [self.phoneText addTarget:self action:@selector(didediting:) forControlEvents:UIControlEventEditingDidBegin];
    [self.phoneText addTarget:self action:@selector(endediting:) forControlEvents:UIControlEventEditingDidEnd];
    [self.passText addTarget:self action:@selector(didediting:) forControlEvents:UIControlEventEditingDidBegin];
    [self.passText addTarget:self action:@selector(endediting:) forControlEvents:UIControlEventEditingDidEnd];
    
    self.ChangeProjectView.frame = CGRectMake(self.view.frame.size.width, 0, self.scrollview.frame.size.width, self.scrollview.frame.size.height);
    [self.ChangeProjectView.btnWith1000 addTarget:self action:@selector(changePro_id:) forControlEvents:UIControlEventTouchUpInside];
    [self.ChangeProjectView.btnWith1001 addTarget:self action:@selector(changePro_id:) forControlEvents:UIControlEventTouchUpInside];
    
    self.ShuRuTGMView.frame = CGRectMake(self.view.width * 2, 0, self.scrollview.frame.size.width, self.scrollview.frame.size.height);
    [self.ShuRuTGMView.jumpBtn addTarget:self action:@selector(jump) forControlEvents:UIControlEventTouchUpInside];
    [self.ShuRuTGMView.sureBtn addTarget:self action:@selector(clickTMG) forControlEvents:UIControlEventTouchUpInside];
    [self.ShuRuTGMView.qrBtn addTarget:self action:@selector(qrCode) forControlEvents:UIControlEventTouchUpInside];
    [self.ShuRuTGMView.TuiGuangCodeText setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];
    self.ShuRuTGMView.TuiGuangCodeText.tintColor = [UIColor whiteColor];
    
    self.scrollview.contentSize = CGSizeMake(self.view.frame.size.width * 3, 0);
    [self.scrollview addSubview:self.ShuRuTGMView];
    [self.scrollview addSubview:self.ChangeProjectView];
    
    [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:NO];

}

#pragma mark - view method
-(void)clickTMG{
    if ([NSString isNullOrEmpty:self.ShuRuTGMView.TuiGuangCodeText.text]) {
        [HUD showErrorMsg:@"信息不能为空"];
        return;
    }
    
    [HUD showLoading:@"提交中..."];
    NSDictionary *parameter ;
   
    parameter = [LRNetwork requestParameter:@{@"promoter_code":self.ShuRuTGMView.TuiGuangCodeText.text}];

    NSString *url = [LRNetwork requestURL:@"cgi/promoter.php"];
    
    [LRNetwork netRequestPOSTWithRequestURL:url withParameter:parameter withReturnValeuBlock:^(id returnValue) {
        
        if (!returnValue[@"mobile"]) {
            [HUD showSucceedMsg:@"记录推广员成功!"];
        }
        [self toMainVC];
    } withErrorCodeBlock:^(NSInteger errorCode, NSString *errorMessage) {
        [HUD showErrorMsg:errorMessage];
    } withFailureBlock:^{
        
    }];
}

-(void)jump{
    [self toMainVC];
}
-(void)closeHMS{
    [self.scrollview setContentOffset:CGPointMake(self.scrollview.frame.size.width * 2, 0) animated:YES];
}
-(void)qrCode{
    
    HMScannerController *scanner = [HMScannerController scannerWithCardName:@"" avatar:nil completion:^(NSString *stringValue) {
        
        NSArray *arr = [stringValue componentsSeparatedByString:@"="];
//        if (arr.count < 2) {
//            return;
//        }
        self.ShuRuTGMView.TuiGuangCodeText.text = arr[0];
        
        [self clickTMG];
        [HUD showMsg:@"扫描结束"];
    }];
    
    [scanner setTitleColor:[UIColor whiteColor] tintColor:[Utils colorWithHexString:allConstHexColor]];
    [self.scrollview setContentOffset:CGPointMake(self.scrollview.frame.size.width * 2, 0) animated:YES];
    [self showDetailViewController:scanner sender:nil];

}

#warning 项目改动
-(void)changePro_id:(UIButton *)sender{
    switch (sender.tag) {
        case 1000:
        {
            allConstNavImgName = @"nav_bg";
            allConstHexColor = @"e85855";
            allConstProjectid = @"7";
            allConstDocPath = @"nbsyBundle.bundle";
            
        }
            break;
            
        case 1001:
        {
            allConstHexColor = @"5750e7";
            allConstNavImgName = @"nav_bgg";
            allConstProjectid = @"6";
            allConstDocPath = @"xgsyBundle.bundle";
        }
            break;
        default:
            break;
    }
    
    NSMutableArray *projArr = [NSMutableArray array];
    [projArr addObject:allConstProjectid];
    NSString *verify = [USER_DEFAULTS objectForKey:@"verify1"];
    allConstMD5id = [Utils md5:[NSString stringWithFormat:@"%@_%@|%@|%@",allConstApp_id,allConstProjectid,allConstMemberid,verify]];
    [USER_DEFAULTS setObject:allConstProjectid forKey:@"allConstProjectid"];
    [USER_DEFAULTS setObject:allConstMD5id forKey:@"verify"];
    [USER_DEFAULTS setObject:allConstHexColor forKey:@"allConstHexColor"];
    [USER_DEFAULTS setObject:allConstNavImgName forKey:@"allConstNavImgName"];
    [USER_DEFAULTS setObject:allConstDocPath forKey:@"allConstDocPath"];
    [USER_DEFAULTS setObject:projArr forKey:@"projArr"];
    [USER_DEFAULTS synchronize];
    
    [self open_promoter];

}
- (IBAction)backKyeborad:(UITapGestureRecognizer *)sender {
    [self.phoneText resignFirstResponder];
    [self.passText resignFirstResponder];
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [self.ShuRuTGMView.TuiGuangCodeText resignFirstResponder];
    [self.phoneText resignFirstResponder];
    [self.passText resignFirstResponder];
}
#pragma mark - Private Method

- (void)open_promoter
{
    NSDictionary *parameter = [LRNetwork requestParameter:@{}];
    NSString *url = [LRNetwork requestURL:@"cgi/reg_project.php"];
    
    [LRNetwork netRequestPOSTWithRequestURL:url withParameter:parameter withReturnValeuBlock:^(id returnValue) {

        allOpen_promoter = returnValue[@"open_promoter"];
        if ([allOpen_promoter integerValue] == 1) {
            [self.ShuRuTGMView.sureBtn setBackgroundColor:[Utils colorWithHexString:@"e85855"]];
            [self.scrollview setContentOffset:CGPointMake(self.scrollview.frame.size.width * 2, 0) animated:YES];
            [self.ShuRuTGMView.TuiGuangCodeText becomeFirstResponder];
        }else{
            [self toMainVC];
        }
        
    } withErrorCodeBlock:^(NSInteger errorCode, NSString *errorMessage) {
        [HUD showErrorMsg:errorMessage];
    } withFailureBlock:^{
        
    }];
}
-(void)toMainVC{
    allOpen_promoter = @"0";
    [self dismissViewControllerAnimated:YES completion:nil];
    ZJTabBarController *vc = [[UIStoryboard storyboardWithName:@"tabBar" bundle:nil] instantiateInitialViewController];
    
    [UIView transitionWithView:[[UIApplication sharedApplication].delegate window]
                      duration:0.4
                       options:UIViewAnimationOptionTransitionCrossDissolve
                    animations:^{
                        BOOL oldState = [UIView areAnimationsEnabled];
                        [UIView setAnimationsEnabled:NO];
                        [[[UIApplication sharedApplication].delegate window] setRootViewController:vc];
                        [UIView setAnimationsEnabled:oldState];
                    } completion:NULL];
}
#pragma mark - 登录
- (IBAction)loginBtn:(RNLoadingButton *)sender {
    [HUD showLoading:@"登录中..."];
    [self.view endEditing:YES];
    NSString *phone = self.phoneText.text;
    NSString *code = self.passText.text;
    
    if ([NSString isNullOrEmpty:phone]) {
        [HUD showErrorMsg:@"请输入电话号码"];
        return;
    }
    if ([NSString isNullOrEmpty:code]) {
        [HUD showErrorMsg:@"请输入验证码"];
        return;
    }
    
    if (![Utils checkContent:code regex:REGEX_NUMBER] || code.length != 6) {
        [HUD showErrorMsg:@"验证码码请输入6位纯数字"];
        return;
    }
    
    if (![Utils checkContent:phone regex:REGEX_PHONE_DEFAULT]) {
        [HUD showErrorMsg:@"请输入正确的电话号码"];
        return;
    }
    
    sender.loading = YES;
    
    [ZJUserModel loginWithPhone:phone password:code withReturnValeuBlock:^(id returnValue) {
        [HUD hide];
        sender.loading = NO;
        [self.scrollview setContentOffset:CGPointMake(self.scrollview.frame.size.width, 0) animated:YES];
    } withErrorCodeBlock:^(NSInteger errorCode, NSString *errorMessage) {
         sender.loading = NO;
        NSLog(@"%@",errorMessage);
        [HUD hide];
    } withFailureBlock:^{
        sender.loading = NO;
        [HUD hide];
    }];
    
}

#pragma mark - 验证码

- (IBAction)getCodeAciton:(JKCountDownButton *)sender {
    NSString *phone = self.phoneText.text;

    if ([NSString isNullOrEmpty:phone]) {
        [HUD showErrorMsg:@"请输入电话号码"];
        return;
    }
    if (![Utils checkContent:phone regex:REGEX_PHONE_DEFAULT]) {
        [HUD showErrorMsg:@"请输入正确的电话号码"];
        return;
    }
    
    sender.enabled = NO;
    [sender startCountDownWithSecond:60];
    [sender countDownChanging:^NSString *(JKCountDownButton *countDownButton,NSUInteger second) {
        NSString *title = [NSString stringWithFormat:@"剩余%zd秒",second];
        return title;
    }];
    [sender countDownFinished:^NSString *(JKCountDownButton *countDownButton, NSUInteger second) { countDownButton.enabled = YES;
        return @"重新发送";
    }];
    NSString *sign = [Utils md5:[NSString stringWithFormat:@"%@|%@_zhejia100_kz9!NF",allConstApp_id,phone]];
    NSDictionary *parameter = @{@"mobile": phone,
                                @"app_id":allConstApp_id,
                                @"sign":sign};
    NSString *url = [LRNetwork requestURL:@"cgi/send_message.php"];
    
    [LRNetwork netRequestPOSTWithRequestURL:url withParameter:parameter withReturnValeuBlock:^(id returnValue) {
        NSLog(@"%@",returnValue);
        
        self.passText.text = returnValue;
        self.passLabel.hidden = YES;
        
        [HUD showSucceedMsg:@"验证码发送成功!"];
    } withErrorCodeBlock:^(NSInteger errorCode, NSString *errorMessage) {
     [HUD showErrorMsg:errorMessage];
    } withFailureBlock:^{
      
    }];
}

#pragma mark - UITextField
-(void)didediting:(UITextField*)textField{
    
    if (textField == self.phoneText) {
        self.phoneLabel.hidden = YES;
    }
    if(textField == self.passText){
        self.passLabel.hidden = YES;
    }

}
-(void)endediting:(UITextField*)textField{
    if (textField.text.length ==0 && textField == self.phoneText) {
        self.phoneLabel.hidden = NO;
    }
    if(textField.text.length ==0 && textField == self.passText){
        self.passLabel.hidden = NO;
    }
}
#pragma mark - UINavigationControllerDelegate

- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    navigationController.navigationBar.hidden =  viewController == self;
}

@end
